package org.linlinjava.litemall.wx.util;

import com.github.pagehelper.Page;
import com.github.pagehelper.dialect.AbstractHelperDialect;
import com.xiaoleilu.hutool.util.ReflectUtil;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.session.RowBounds;


public abstract class MybatisPermissionDialect extends AbstractHelperDialect{
    /**
     * 单独处理分页部分
     *
     * @param sql
     * @param page
     * @param pageKey
     * @return
     */
    @Override
    public String getPageSql(String sql, Page page, CacheKey pageKey) {
        StringBuilder sqlBuilder = new StringBuilder(sql.length() + 14);
        sqlBuilder.append(sql);
        if (page.getStartRow() == 0) {
            sqlBuilder.append(" LIMIT ");
            sqlBuilder.append(page.getPageSize());
        } else {
            sqlBuilder.append(" LIMIT ");
            sqlBuilder.append(page.getStartRow());
            sqlBuilder.append(",");
            sqlBuilder.append(page.getPageSize());
            pageKey.update(page.getStartRow());
        }
        pageKey.update(page.getPageSize());
        return sqlBuilder.toString();
    }

    @Override
    public Object processParameterObject(MappedStatement ms, Object parameterObject, BoundSql boundSql, CacheKey pageKey) {
        // ReflectUtil.setFieldValue(boundSql, "sql", permissionSql(ms, boundSql.getSql()));
        return super.processParameterObject(ms, parameterObject, boundSql, pageKey);
    }

    @Override
    public String getCountSql(MappedStatement ms, BoundSql boundSql, Object parameterObject, RowBounds rowBounds, CacheKey countKey) {
        ReflectUtil.setFieldValue(boundSql, "sql", permissionSql(ms, boundSql.getSql()));
        return super.getCountSql(ms, boundSql, parameterObject, rowBounds, countKey);
    }


    @Override
    public String getPageSql(MappedStatement ms, BoundSql boundSql, Object parameterObject, RowBounds rowBounds, CacheKey pageKey) {
        return super.getPageSql(ms, boundSql, parameterObject, rowBounds, pageKey);
    }


    public abstract String permissionSql(MappedStatement ms, String sql);

}
